import pygame
import random
from constants import SCREEN_HEIGHT, SCREEN_WIDTH


class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
        self.rect = self.image.get_rect()
        # 玩家方块生成的初始位置
        self.rect.center = (50, 0)
        self.in_air = True
        # 玩家方块的重力加速度
        self.g = 0.3
        # 玩家方块的向上初速度
        self.v = 0
        # 落地反弹时的动能衰减系数
        self.n = 0.75

    def update(self):
        # 左右键的速度
        speed = 5
        self.rect.move_ip(0, 0)
        # 判断玩家方块是否在空中
        if self.rect.bottom < SCREEN_HEIGHT:
            self.in_air = True
        else:
            self.in_air = False
        # 如果在空中，自由落体落下
        if self.in_air:
            self.v += self.g
            self.rect.bottom += self.v

        # 获取按键信号
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.rect.left -= speed
            if self.rect.left < 0:
                self.rect.left = 0
        if keys[pygame.K_RIGHT]:
            self.rect.right += speed
            if self.rect.right > SCREEN_WIDTH:
                self.rect.right = SCREEN_WIDTH
        if not self.in_air and keys[pygame.K_SPACE]:
            pygame.mixer.Sound('reserve/sound/small_jump.ogg').play()
            self.v = -12.2
            self.v += self.g
            self.rect.bottom += self.v

